package cn.itcast.mybatis.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.itcast.mybatis.dao.IUserDao;
import cn.itcast.mybatis.po.User;

public class UserDaoImpl implements IUserDao {

	private SqlSessionFactory sqlSessionFactory;
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	@Override
	public User findUserById(Integer id) {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = null;
		try {
			user = sqlSession.selectOne("test.findUserById", id);
		} finally{
			sqlSession.close();
		}
		return user;
	}

	@Override
	public List<User> findUserByName(String username) {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<User> users = null;
		try {
			users = sqlSession.selectList("test.findUserByName", username);
		} finally{
			sqlSession.close();
		}
		return users;
	}

	@Override
	public void insertUser(User user) {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			sqlSession.insert("test.insertUser",user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			sqlSession.commit();
			sqlSession.close();
		}
	}

}
